const { Resource, User } = require('../models');
const { Op } = require('sequelize');

// 获取资源列表
const getResources = async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      category, 
      type, 
      difficulty, 
      search,
      isFree
    } = req.query;

    const whereCondition = { is_active: true };

    // 分类筛选
    if (category) {
      whereCondition.category = category;
    }

    // 类型筛选
    if (type) {
      whereCondition.type = type;
    }

    // 难度筛选
    if (difficulty) {
      whereCondition.difficulty = difficulty;
    }

    // 免费筛选
    if (isFree !== undefined) {
      whereCondition.is_free = isFree === 'true';
    }

    // 搜索
    if (search) {
      whereCondition[Op.or] = [
        { title: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } }
      ];
    }

    const { count, rows } = await Resource.findAndCountAll({
      where: whereCondition,
      include: [{
        model: User,
        as: 'creator',
        attributes: ['id', 'username', 'real_name']
      }],
      order: [['sort_order', 'DESC'], ['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: (parseInt(page) - 1) * parseInt(limit)
    });

    res.json({
      resources: rows,
      pagination: {
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(count / parseInt(limit))
      }
    });
  } catch (error) {
    console.error('获取资源列表错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 获取资源详情
const getResourceById = async (req, res) => {
  try {
    const { id } = req.params;

    const resource = await Resource.findOne({
      where: { id, is_active: true },
      include: [{
        model: User,
        as: 'creator',
        attributes: ['id', 'username', 'real_name']
      }]
    });

    if (!resource) {
      return res.status(404).json({ message: '资源不存在' });
    }

    // 增加浏览次数
    await resource.increment('view_count');

    res.json({ resource });
  } catch (error) {
    console.error('获取资源详情错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 创建资源（需要教师或管理员权限）
const createResource = async (req, res) => {
  try {
    const {
      title,
      description,
      type,
      category,
      url,
      thumbnail,
      difficulty = 'beginner',
      tags = [],
      isFree = true,
      language = 'zh',
      sortOrder = 0
    } = req.body;

    if (!title || !type || !category || !url) {
      return res.status(400).json({ message: '标题、类型、分类和链接都是必填项' });
    }

    const resource = await Resource.create({
      title,
      description,
      type,
      category,
      url,
      thumbnail,
      difficulty,
      tags,
      is_free: isFree,
      language,
      sort_order: sortOrder,
      created_by: req.user.id
    });

    res.status(201).json({
      message: '资源创建成功',
      resource
    });
  } catch (error) {
    console.error('创建资源错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 更新资源
const updateResource = async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    const resource = await Resource.findByPk(id);

    if (!resource) {
      return res.status(404).json({ message: '资源不存在' });
    }

    // 检查权限：只有创建者、教师或管理员可以修改
    if (resource.created_by !== req.user.id && !['teacher', 'admin'].includes(req.user.role)) {
      return res.status(403).json({ message: '权限不足' });
    }

    await resource.update(updateData);

    res.json({
      message: '资源更新成功',
      resource
    });
  } catch (error) {
    console.error('更新资源错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 删除资源（软删除）
const deleteResource = async (req, res) => {
  try {
    const { id } = req.params;

    const resource = await Resource.findByPk(id);

    if (!resource) {
      return res.status(404).json({ message: '资源不存在' });
    }

    // 检查权限
    if (resource.created_by !== req.user.id && !['teacher', 'admin'].includes(req.user.role)) {
      return res.status(403).json({ message: '权限不足' });
    }

    await resource.update({ is_active: false });

    res.json({ message: '资源删除成功' });
  } catch (error) {
    console.error('删除资源错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 点赞资源
const likeResource = async (req, res) => {
  try {
    const { id } = req.params;

    const resource = await Resource.findOne({
      where: { id, is_active: true }
    });

    if (!resource) {
      return res.status(404).json({ message: '资源不存在' });
    }

    await resource.increment('like_count');

    res.json({ 
      message: '点赞成功',
      likeCount: resource.like_count + 1
    });
  } catch (error) {
    console.error('点赞资源错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 获取资源分类统计
const getResourceStats = async (req, res) => {
  try {
    // 按分类统计
    const categoryStats = await Resource.findAll({
      where: { is_active: true },
      attributes: [
        'category',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['category']
    });

    // 按类型统计
    const typeStats = await Resource.findAll({
      where: { is_active: true },
      attributes: [
        'type',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['type']
    });

    // 按难度统计
    const difficultyStats = await Resource.findAll({
      where: { is_active: true },
      attributes: [
        'difficulty',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['difficulty']
    });

    // 热门资源
    const popularResources = await Resource.findAll({
      where: { is_active: true },
      order: [['view_count', 'DESC']],
      limit: 5,
      attributes: ['id', 'title', 'view_count', 'like_count']
    });

    res.json({
      categoryStats,
      typeStats,
      difficultyStats,
      popularResources
    });
  } catch (error) {
    console.error('获取资源统计错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

module.exports = {
  getResources,
  getResourceById,
  createResource,
  updateResource,
  deleteResource,
  likeResource,
  getResourceStats
}; 